package cn.ycq.im.chat.handle;

import cn.ycq.im.chat.CmdHandler;
import cn.ycq.im.chat.CmdTransport;
import cn.ycq.im.chat.CmdType;
import cn.ycq.im.chat.MessageBuildUtils;
import cn.ycq.im.chat.clients.ChannelAttributeUtils;
import cn.ycq.im.chat.clients.ChannelListWraper;
import cn.ycq.im.chat.clients.ClientManager;
import com.alibaba.fastjson.JSON;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.Optional;

public class LoginCmdHandle implements CmdHandler {

    @Override
    public CmdType getCmdType() {
        return CmdType.LOGIN;
    }

    @Override
    public void handle(ChannelHandlerContext ctx, CmdTransport cmdTransport) {
        String name = (String) cmdTransport.get("name");

        ChannelAttributeUtils.setAttribute("userName", ctx.channel(), name);
        ClientManager.addClient(ctx.channel(), name);


        ChannelListWraper clientListWrapper = ClientManager.getClientListWrapper(name);

        CmdTransport meSystemMessage = MessageBuildUtils.getSystemMessage("欢迎你登陆聊天室");
        CmdTransport youSystemMessage = MessageBuildUtils.getSystemMessage(String.format("%s进入聊天室", name));

        if (clientListWrapper == null || !clientListWrapper.isInit()) {
            ClientManager.writeAndFlusFuncEach((n, clist) -> {
                if (n.equals(name)) {
                    clist.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(meSystemMessage)));
                } else {
                    clist.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(youSystemMessage)));
                }
            });
            Optional.ofNullable(clientListWrapper).ifPresent(ChannelListWraper::inited);
        }else{
             ctx.channel().writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(meSystemMessage)));
        }
    }
}
